#include "SampleUploaderPlugin.h"
#include <QtDebug>




SampleUploaderPlugin::SampleUploaderPlugin() : AbstractUploader(), authorizedAlready(false) {
	About.Name          = "SamplePlugin";
	About.Description   = "Sample BASED uploader plugin. QNetworkManager.";
	About.Hosting       = "mediacenter test hosting";
	About.HostingUrl    = "http://www.imagehost.org/";
	About.Author        = "Name_No (Nick Malakhov)";
	About.email         = "nomen.infitior@gmail.com";
	About.version       = "0.0";
	About.CmdlParameter = "sample";
	About.icon          = QIcon(":/Icon/image.png");

//	Hosting.Host    = "mediacenter";
//	Hosting.URI     = "/post.php";
//	Hosting.URL     = "http://mediacenter/post.php";

	Hosting.Host    = "www.imagehost.org";
	Hosting.URI     = "/";
	Hosting.URL     = "http://www.imagehost.org/";

	Hosting.User_Agent = "Opera/9.80 (X11; Linux i686; U; ru) Presto/2.2.15 Version/10.10";

}

void SampleUploaderPlugin::authorizeAndUpload() {
	if (authorizedAlready) {
		emit authorized();
		return;
	}
	QNetworkRequest req(QUrl(Hosting.URL));
	mainPage = getNetManager()->get(req);
	connect(mainPage, SIGNAL(finished()), this, SLOT(authSecondStep()));
	connect(mainPage, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(sAuthError(QNetworkReply::NetworkError)));
}

void SampleUploaderPlugin::authSecondStep() {
	QString mainPageHTML = mainPage->readAll();
	mainPage->disconnect(this, SLOT(authSecondStep()));
	mainPage->disconnect(this, SLOT(sAuthError(QNetworkReply::NetworkError)));
	mainPage->deleteLater();
	QRegExp verImgRX("(\\\?p=verify[^\"]+)\" ");
	verImgRX.setMinimal(true);
	QString verifyURL;
	if (mainPageHTML.contains(verImgRX)) {
		if ( verImgRX.indexIn(mainPageHTML, 0) != -1 ) {
			verifyURL = verImgRX.cap(1);
		}
	}
	verifyURL.replace("&amp;", "&");
	qDebug() << "verifyURL" << verifyURL;
	QNetworkRequest req(QUrl(Hosting.URL+verifyURL));
	req.setRawHeader("Referer", QByteArray().append(Hosting.URL));
	verifyPage = getNetManager()->get(req);
	connect(verifyPage, SIGNAL(finished()), this, SLOT(authReqFinished()));
	connect(verifyPage, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(sAuthError(QNetworkReply::NetworkError)));
}

void SampleUploaderPlugin::authReqFinished() {
	qDebug() << verifyPage->rawHeaderList();
	verifyPage->deleteLater();
	authorizedAlready = true;
	emit authorized();
}

void SampleUploaderPlugin::sAuthError(QNetworkReply::NetworkError err) {
	qWarning() << "auth error:" << err;
	requestAborted = true;
	const QMetaObject* mo = verifyPage->metaObject();
	QString error = QString("Can't authorize: ").append(mo->enumerator(mo->indexOfEnumerator("NetworkError")).valueToKey(err));
	emit authError(error);
}

Q_EXPORT_PLUGIN2(SampleUploader, SampleUploaderPlugin);
